<template>
  <div class="publish-container">
    <van-nav-bar class="bgcolor" title="发布动态" @click-right="publishAction">
      <template #right>
        <span class="publish-button">发布</span>
      </template>
    </van-nav-bar>

    <div class="main-content">
      <div class="publish-message">
        <van-field
          v-model="content"
          rows="5"
          autosize
          type="textarea"
          maxlength="150"
          placeholder="分享今天的美食吧"
          show-word-limit
        />
      </div>

      <div class="publish-image">
        <van-uploader
          :after-read="afterRead"
          v-model="fileList"
          multiple
          :max-count="9"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { publishAction } from "@/api/community";
import { uploadImage } from "@/api/uploadImage";
import { mapState } from "vuex";
export default {
  name: "PublishAction",

  data() {
    return {
      content: "",
      fileList: [],
      submitFileList: [],
    };
  },

  computed: {
    ...mapState("user", ["user"]),
  },

  mounted() {},

  methods: {
    publishAction() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "正在发布，请稍后...",
      });

      /**
       * 1.将fileList中的图片上传服务器，返回的数据保存到submitFileList中
       * 2.将文件与此次的动态一同发布
       * 3.清空subbmitFileList
       */

      this.traversalFileList().then((res) => {
        let date = new Date();
        let month = date.getMonth() + 1;

        let action = {
          actTime:
            date.getFullYear() +
            "-" +
            month +
            "-" +
            date.getDay() +
            " " +
            date.getHours() +
            ":" +
            date.getMinutes() +
            ":" +
            date.getSeconds(),
          content: this.content,
          author: this.user,
          images: this.submitFileList,
        };

        publishAction(action).then((res) => {
          this.fileList = [];
          this.content = "";
          this.submitFileList = [];
          this.$toast.clear();
          this.$toast.success("发布成功，请刷新");
          setTimeout(() => {
            this.$router.replace({
              name: "community",
            });
          }, 2000);
        });
      });
    },

    traversalFileList() {
      let that = this;
      return new Promise(function (resolve, reject) {
        that.fileList.forEach((item) => {
          let formData = new FormData();
          formData.append("file", item.file);
          uploadImage(formData)
            .then((res) => {
              that.submitFileList.push(
                "/upload" + res.data.split("/upload")[1]
              );
              if (that.submitFileList.length == that.fileList.length) {
                resolve(res);
              }
            })
            .catch((err) => {
              reject(new Error(err.statusText));
            });
        });
      });
    },

    /**
     * fileList绑定后它里面的文件时base64转码，这不是我们想要的结果，所以我们需要去动态的替换
     *
     * 这里并不适合上传，因为上传组件绑定的fileList不是上传至服务器的数据，如果自己去维护的话，可能会陷入一个坑里
     * 所以我们在用户点击发表时上传图片，这样一方面不用自己维护文件上传数组，一方面为服务器减少不必要的图片上传，降低压力
     */
    afterRead(fileParams) {
      // this.submitFileList = [];
      // // 此时可以自行将文件上传至服务器
      // console.log("this.fileList", this.fileList[0].file);
      // if (Array.isArray(fileParams)) {
      //   fileParams.forEach((item) => {
      //     let formData = new FormData();
      //     formData.append("file", item.file);
      //     uploadImage(formData).then((res) => {
      //       let file = { url: res.data };
      //       // this.fileList.push(file);
      //       res.data.split("/upload");
      //       this.submitFileList.push({
      //         url: "/upload" + res.data.split("/upload")[1],
      //       });
      //       console.log("upload res = ", res);
      //     });
      //   });
      //   return;
      // }
      // let formData = new FormData();
      // formData.append("file", fileParams.file);
      // uploadImage(formData).then((res) => {
      //   let file = { url: res.data };
      //   console.log("file = ", file);
      //   // this.fileList.push(file);
      //   this.submitFileList.push({
      //     url: "/upload" + res.data.split("/upload")[1],
      //   });
      //   console.log("upload res = ", res);
      // });
    },
  },
};
</script>

<style lang="less" scoped>
.bgcolor {
  background-color: rgb(153, 217, 157);
  color: #000;
}

.publish-button {
  width: 40px;
  text-align: center;
  font-size: 15px;
  color: #fa921d;
}

.publish-container {
  .main-content {
    width: 100%;
    height: auto;
    margin: 5px 0;
    box-sizing: border-box;
    padding: 10px;
    background-color: #fff;

    .publish-message {
      width: 100%;
      min-height: 175px;
    }

    .publish-image {
      width: 100%;
      min-height: 100px;
      height: auto;
    }
  }
}
</style>